# Maintainer: LI Xuzhang <lixuzhang@gmail.com>

_realname=postgis
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=3.5.0
pkgrel=2
pkgdesc="Spatial and Geographic objects for PostgreSQL (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://postgis.net/"
msys2_repository_url="https://git.osgeo.org/gitea/postgis/postgis"
msys2_references=(
  'archlinux: postgis'
  "cpe: cpe:/a:postgis:postgis"
)
license=('spdx:GPL-2.0-or-later')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-geos"
         "${MINGW_PACKAGE_PREFIX}-gettext-runtime"
         "${MINGW_PACKAGE_PREFIX}-json-c"
         "${MINGW_PACKAGE_PREFIX}-libiconv"
         "${MINGW_PACKAGE_PREFIX}-libxml2"
         "${MINGW_PACKAGE_PREFIX}-pcre2"
         "${MINGW_PACKAGE_PREFIX}-postgresql"
         #"${MINGW_PACKAGE_PREFIX}-protobuf-c"
         "${MINGW_PACKAGE_PREFIX}-proj"
         "${MINGW_PACKAGE_PREFIX}-gdal"
         "${MINGW_PACKAGE_PREFIX}-sfcgal")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-autotools"
             "${MINGW_PACKAGE_PREFIX}-libxslt")
source=("https://download.osgeo.org/postgis/source/${_realname}-${pkgver}.tar.gz"
        pg_config
        0001-clang-postgresql.patch
        0002-disable-doc.patch
        0003-remove-redeclaration.patch)
sha256sums=('ca698a22cc2b2b3467ac4e063b43a28413f3004ddd505bdccdd74c56a647f510'
            '3cd5a095cd4de7cb7d5f5fa9dbc02dfe02297ae1743c2961e70d9110d214f64f'
            '5e3a39bdacbbb6825206df61c49a0479da8d6201ff78423fc0bdbeaf44b70e3d'
            '69bfda9f0021bce623eba952f423801fde618cc4913197dcb79a78d9cf0265b6'
            '2fd6fa459548e2f9d29456a7c7e9f4267898c8f85446ecf762468a233a6e73db')

apply_patch_with_msg() {
  for _fname in "$@"
  do
    msg2 "Applying ${_fname}"
    patch -Nbp1 -i "${srcdir}"/${_fname}
  done
}

prepare() {
  cd ${_realname}-${pkgver}

  if [[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]]; then
    apply_patch_with_msg \
      0001-clang-postgresql.patch \
      0003-remove-redeclaration.patch
  fi

  apply_patch_with_msg \
    0002-disable-doc.patch

  ./autogen.sh
}

build() {
  mkdir -p "${srcdir}"/build-${MSYSTEM} && cd "${srcdir}"/build-${MSYSTEM}

  # workaround to fix linking PostgreSQL with clang
  if [[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]]; then
    export LIBS="-lc++"
  fi

  CFLAGS+=" -Wno-implicit-function-declaration" \
  CXXFLAGS+=" -std=gnu++17" \
  ../${_realname}-${pkgver}/configure \
    --prefix=${MINGW_PREFIX} \
    --without-protobuf \
    --with-pgconfig="${srcdir}"/pg_config

  make
}

package() {
  cd "${srcdir}"/build-${MSYSTEM}
  make DESTDIR="${pkgdir}" install
  install -Dm644 "${srcdir}"/${_realname}-${pkgver}/COPYING \
    "${pkgdir}"${MINGW_PREFIX}/share/licenses/${_realname}/COPYING
}
